#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    connect_capture_to_handler();
    default_setting();
    tryload_config(data_map["config_out"]);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::closeEvent(QCloseEvent *event)
{
    if(is_edit_tablewidget)
    {
        if(data_map["xlsx_out"].isEmpty()){
            ui->actionExport_To_Excel->triggered();
        }
        else
            xlsx_save(data_map["xlsx_out"]);
    }
    event->accept();
}


void MainWindow::connect_capture_to_handler()
{
    connect(ui->qterm, SIGNAL(captureToMain(QString)), this, SLOT(capture_from_qterm(QString)), Qt::QueuedConnection);
    connect(this, SIGNAL(cmd_result(QString)), this, SLOT(cmd_result_slot(QString)), Qt::QueuedConnection);
}

void MainWindow::capture_from_qterm(QString text)
{
    if(text != last_capture){
        qDebug()<<"From capture_from_qterm: "<<text;
        QString tmp = filter_result(text);
        if(!tmp.isEmpty())
            pick_up_result(tmp);
    }
    last_capture = text;
}
/*
 * Filter and Return Useful Information QString From Text
 * A string line which does not contain \r\n would be append to capture_buf.
 * A string line which's not endwith \r\n would be reconstruct
 * and the last part split with \r\n would be append to capture_buf.
 * A string which's split with \r\n from the string line contains && or || or echo would be tick out.
*/
QString MainWindow::filter_result(QString text)
{
    unsigned int i,count = 0;
    QString ret, tmp1;
    QStringList strl;
    if(!text.contains("\r\n")){
        capture_buf.append(text);
        ret = "";
    }else{
        if(capture_buf.isEmpty()){
            strl = text.split("\r\n");
        }else{
            tmp1 = capture_buf;
            tmp1.append(text);
            strl = tmp1.split("\r\n");
            capture_buf = "";
        }
        tmp1 = "";
        count = strl.size();
        if(!text.endsWith("\r\n")){
            capture_buf = strl[strl.size()-1];
            count -=1;
        }
        for(i = 0 ;i < count; i++){
            if(!strl[i].contains("&&") && !strl[i].contains("||") && !strl[i].contains("echo")){
                tmp1.append(strl[i]);
                tmp1.append("\r\n");
            }
        }
        ret = tmp1;
        qDebug()<<"From filter_result: "<<ret;
    }
    return ret;
}

void MainWindow::default_setting()
{
    is_run_one_cmd_next = false;
    run_one_cmd_res = false;
    is_detect_ip = false;
    is_ssh = false;
    dev_count = 0;
    dev_type = "NA";
    last_capture = "";
    capture_buf = "";
    last_ip = "";

    //Device Type
    all_dev_type_name.append(PRODUCT_NAME_SS_2G12_8);
    all_dev_type_name.append(PRODUCT_NAME_SS_2G12_16);
    all_dev_type_name.append(PRODUCT_NAME_SS_5G16_8);
    all_dev_type_name.append(PRODUCT_NAME_SS_5G16_16);
    all_dev_type_name.append(PRODUCT_NAME_PB_5G20_8);
    all_dev_type_name.append(PRODUCT_NAME_PB_5G20_16);
    all_dev_type_name.append(PRODUCT_NAME_PB_5G23_8);
    all_dev_type_name.append(PRODUCT_NAME_PB_5G23_16);
    all_dev_type_name.append(PRODUCT_NAME_PB_5G25_8);
    all_dev_type_name.append(PRODUCT_NAME_PB_5G25_16);
    all_dev_type_name.append(PRODUCT_NAME_STATION5_8);
    all_dev_type_name.append(PRODUCT_NAME_STATION5_16);
    all_dev_type_name.append(PRODUCT_NAME_OS_5G12_8);
    all_dev_type_name.append(PRODUCT_NAME_OS_5G12_16);
    all_dev_type_name.append(PRODUCT_NAME_DB_5G25_8);
    all_dev_type_name.append(PRODUCT_NAME_DB_5G25_16);

    //settings' name
    opt_map.insert(SSHIP, "ssh_ip");
    opt_map.insert(SSHUSER, "ssh_user");
    opt_map.insert(SSHPASSWORD, "ssh_password");
    opt_map.insert(DHCPLOGFILE, "dhcp_log_file");
    opt_map.insert(STARTSH, "start_sh");
    opt_map.insert(STOPSH, "stop_sh");
    opt_map.insert(XLSXOUT, "xlsx_out");
    opt_map.insert(CONFIGOUT, "config_out");
    opt_map.insert(SERVERIP, "server_ip");
    opt_map.insert(BOARDCONFIGFILEFULLNAME, "config_test_board_config_path");
    opt_map.insert(UPGRADEFRAMWORKFULLNAME, "upgrade_test_img_path");
    opt_map.insert(LICENSESTRING, "license_test");
    opt_map.insert(WIFIAPSSID, "wifi_test_ssid");
    opt_map.insert(WIFIIP, "wifi_test_ip");
    opt_map.insert(MACSCAN, "mac_test_mac");

    opt_map.insert(PARTITIONUBOOT, "u-boot");
    opt_map.insert(PARTITIONUBOOTENV, "u-boot-env");
    opt_map.insert(PARTITIONCFG1, "cfg1");
    opt_map.insert(PARTITIONCFG2, "cfg2");
    opt_map.insert(PARTITIONOME, "oem");
    opt_map.insert(PARTITIONDEFAULT, "default");
    opt_map.insert(PARTITIONMFG, "mfg");
    opt_map.insert(CURRENTPARTITION, opt_map[PARTITIONOME]);

    opt_map.insert(SPECIALCMDEXIT, "exit");
    opt_map.insert(SPECIALCMDSTARTSHELL, "superman");

    //default setting
    data_map.insert("ssh_ip", "localhost");
    data_map.insert("ssh_password", "password");
    data_map.insert("ssh_user", "vjjt");
    data_map.insert("dhcp_log_file", "/var/log/messages");
    data_map.insert("dhcp_log_file_filter_key_word", "DHCPOFFER");
    data_map.insert("ssh_cmdline", "ssh   "+data_map["ssh_user"]+ "@"+data_map["ssh_ip"]+"\n");
    data_map.insert("rand_mac", "00:00:00:00:00:00");
    data_map.insert("config_out", "/vjjtUI/vjjtUI.cfg");
    data_map.insert("start_sh", "/vjjtUI/vjjtstart.sh");
    data_map.insert("stop_sh", "/vjjtUI/vjjtstop.sh");
    data_map.insert("xlsx_out", "/vjjtUI/results.xlsx");
    data_map.insert("dhcp_ip_cmd", "ping "+data_map["ssh_ip"]+" -c 3" + "&& echo dhcp_ip_OK || echo dhcp_ip_FAIL");
    data_map.insert("server_ip", "192.168.1.2");
    data_map.insert("config_test_board_config_path", "/result/config-"+dev_type+".bin");
    data_map.insert("upgrade_test_img_path", "/result/ap.img");
    data_map.insert("license_test", generate_license(dev_type));
    data_map.insert("wifi_test_ssid", "DoggerAndPigger");
    data_map.insert("wifi_test_ip", "192.168.55.1");
    data_map.insert("mac_test_mac", "B0966C000000");

    //The following keys aim to figure out the result of the current shell command, it's succcess of fail
    capture_key_map.insert(CMDEXITSUCCESSKEY, "cmd_exit_success");
    capture_key_map.insert(CMDEXITFAILKEY, "cmd_exit_fail");
    capture_key_map.insert(CMDTIMEOUTFAILKEY, "cmd_run_timeout");

    //The followings is commandline standard outputvcapture key
    capture_key_map.insert(TYPEKEY, "type");
    capture_key_map.insert(MACKEY, "MAC");
    capture_key_map.insert(LAN1KEY, "LAN1");
    capture_key_map.insert(LAN2KEY, "LAN2");
    capture_key_map.insert(CONFIGKEY, "CONFIG");
    capture_key_map.insert(WIFIKEY, "WIFI");
    capture_key_map.insert(LEDKEY, "LED");
    capture_key_map.insert(RESETKEY, "RESET");
    capture_key_map.insert(WATCHDOGKEY, "WATCHDOG");
    capture_key_map.insert(LICENSEKEY, "LICENSE");
    capture_key_map.insert(UPGRADEKEY, "UPGRADE--");
    capture_key_map.insert(UPMTDKEY, "UPGRADE-"+opt_map[CURRENTPARTITION]);
    capture_key_map.insert(PASSKEY, "PASS");
    capture_key_map.insert(FAILKEY, "FAIL");
    capture_key_map.insert(NAKEY, "NA");
    capture_key_map.insert(SSHLOGINKEY, "press TAB again to see");

    //The following is command line capture key
    capture_key_map.insert(SPECIALLAN1CMD, "lan1_test");
    capture_key_map.insert(SPECIALLAN2CMD, "lan2_test");
    capture_key_map.insert(SPECIALCONFIGCMD, "config_test");
    capture_key_map.insert(SPECIALUPMTDCMD, "upmtd_test");
    capture_key_map.insert(SPECIALMACCMD, "mac_test");
    capture_key_map.insert(SPECIALLICENSECMD, "license_test");
    capture_key_map.insert(SPECIALUPGRADECMD, "upgrade_test");
    capture_key_map.insert(SPECIALLEDCMD, "led_test");
    capture_key_map.insert(SPECIALWIFICMD, "wifi_test");
    capture_key_map.insert(SPECIALRESETCMD, "reset_test");
    capture_key_map.insert(SPECIALWATCHDOGCMD, "watchdog_test");

    //The SSHLOGINKEY is use to figure out whether it's login the target board successfully
    is_config = false;
    is_edit_tablewidget = false;

    settingdialog = new SettingDialog(this, data_map["ssh_user"], data_map["ssh_ip"], data_map["ssh_password"], data_map["dhcp_log_file"]);

    timer = new QTimer;
    connect(timer, SIGNAL(timeout()), this, SLOT(update_time()));
    timer->start(1000);
    delay_success_timer = new QTimer;
    connect(delay_success_timer, SIGNAL(timeout()), this, SLOT(emit_success_result_timer()));
    delay_fail_timer = new QTimer;
    connect(delay_fail_timer, SIGNAL(timeout()), this, SLOT(emit_fail_result_timer()));

    ui->devtypebox->addItems(all_dev_type_name);
    ui->macline->setReadOnly(true);
    ui->macline->setText("NA");
    QStringList strl;
    strl<<"TYPE"<<"LAN1"<<"LAN2"<<"CONFIG"<<"UPMTD"<<"MAC"<<"LICENSE"<<"UPGRADE"<<"LED"<<"WIFI"<<"RESET"<<"WATCHDOG";
    ui->resulttable->setColumnCount(12);
    ui->resulttable->setRowCount(dev_count+1);
    ui->resulttable->setHorizontalHeaderLabels(strl);
    ui->resulttable->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->resulttable->setSelectionMode(QAbstractItemView::SingleSelection);
}

QString MainWindow::generate_license(QString license)
{
    int len = license.length();
    QString res = license;
    if(len<=13){
        len = 13-len;
        while(len>=1){
            res.append("0");
            len--;
        }
    }else{
        res = license.left(13);
    }
    return res;
}

bool MainWindow::tryload_config(QString config_file)
{
    QFileInfo qinfo(config_file);
    if(!qinfo.isFile()){
        is_config = false;
        return false;
    }
    QFile file(config_file);
    if(!file.open(QFile::ReadOnly | QFile::Text)){
        QMessageBox::warning(this, tr("Application"),
                             tr("Can not read config file %1:\n"
                                "%2").arg(config_file)
                             .arg(file.errorString()));
        return false;
    }
    QTextStream in(&file);
    QString line;
    QStringList strl;
    line = in.readLine();
    while(!line.isEmpty()){
        strl = line.split("=");
        if(strl.size()>1 && data_map.contains(strl[0])){
            switch(opt_map.key(strl[0])){
            case SSHIP:
                data_map["ssh_ip"] = strl[1];
                qDebug()<<data_map["ssh_ip"];
                break;
            case SSHPASSWORD:
                data_map["ssh_password"] = strl[1];
                qDebug()<<data_map["ssh_password"];
                break;
            case DHCPLOGFILE:
                data_map["dhcp_log_file"] = strl[1];
                qDebug()<<data_map["dhcp_log_file"];
                break;
            case STARTSH:
                data_map["start_sh"] = strl[1];
                qDebug()<<data_map["start_sh"];
                break;
            case STOPSH:
                data_map["stop_sh"] = strl[1];
                qDebug()<<data_map["stop_sh"];
                break;
            case XLSXOUT:
                data_map["xlsx_out"] = strl[1];
                qDebug()<<data_map["xlsx_out"];
                break;
            case SERVERIP:
                data_map["server_ip"] = strl[1];
                qDebug()<<data_map["server_ip"];
            }
        }
        line = in.readLine();
    }
    is_config = true;
    return true;
}

bool MainWindow::run_vjjt_test_script(QString fileName)
{
    QFileInfo qinfo(fileName);
    if(!qinfo.isFile()){
        QMessageBox::critical(this, tr("Error Finding Script"), tr("Can not Find Script to "
                                                                         "Run Test Service! You Must Put you Script At <br>"
                                                                         "<b> /vjjtUI/vjjtstart.sh Or /vjjtUI/vjjtstop.sh</b> Or Setting the "
                                                                         "<b> start_sh=YourPathToStartScript "
                                                                   "stop_sh = YourPathToStopScript</b>"));
        return false;
    }
    QFile file(fileName);
    if(!file.open(QFile::ReadOnly | QFile::Text)){
        QMessageBox::critical(this, tr("Error While Opening cript"), tr("Can not Open the Script at"
                                                                               "<b>%1</b><br>"
                                                                               "May be you should check the mode setting of this file!").arg(fileName));
        return false;
    }
    QTextStream in(&file);
    QString line;
    line = in.readLine();
    while(!line.isEmpty()){
        line = filter_cmd_line(line);
        if(line.isEmpty()){
            line = in.readLine();
            continue;
        }
        if(!run_one_cmd(line)){
            if(!QMessageBox::Yes == QMessageBox::question(this, tr("Error While Running Script"), tr("Some Error Seens to be occured "
                                                                                                    "while running scritp: <b> %1 </b> <br>"
                                                                                                    "at command line: <b> %2 </b> <br>"
                                                                                                    "Would you like to continue? yes or no")
                                                         .arg(fileName).arg(line),
                                                         QMessageBox::Yes | QMessageBox::No,QMessageBox::Yes)){
                return false;
            }
        }
        line = in.readLine();
    }
    return true;
}

/*
 * To add additional parameters to cmdline from start script or stop script
*/
QString MainWindow::filter_cmd_line(QString line)
{
    QString res = "";
    int j = 0;
    for(j = SPECIALCMD_START ;j<= SPECIALCMD_STOP ; j++)
    {
        if(line.contains(capture_key_map[j]))
        {
            res = capture_key_map[j];
            switch(j){
            case SPECIALLAN1CMD:
            case SPECIALLAN2CMD:
                res += " " + data_map["server_ip"];
                break;
            case SPECIALCONFIGCMD:
                res += " " + dev_type + " " + data_map["config_test_board_config_path"];
                break;
            case SPECIALUPMTDCMD:
                res += (QString)" " + "oem" + " /result/oem";
                break;
            case SPECIALMACCMD:
                res += " " + data_map["mac_test_mac"];
                break;
            case SPECIALLICENSECMD:
                res += " " + generate_license(dev_type);//templine
                break;
            case SPECIALUPGRADECMD:
                res += " " + data_map["upgrade_test_img_path"];
                break;
            case SPECIALWIFICMD:
                res += " " + data_map["wifi_test_ssid"] + " " + data_map["wifi_test_ip"];
                break;
            case SPECIALWATCHDOGCMD:
                res += (QString)"  5";
                break;
            case SPECIALRESETCMD:
            case SPECIALLEDCMD:
                break;
            }
        }
    }
    return res;
}

/*
 * pick up some results from text which contains substring matching CAPTURE key.
 * and send signals to break run_one_cmd loop after getting a single cmd running result:
 * cmd_exit_success OR cmd_exit_fail .
*/
void MainWindow::pick_up_result(QString text)
{
    int i,j;
    QString str;
    QStringList strl;
    if(text.contains("\r\n")){
        strl = text.split("\r\n");
    }else{
        strl.append(text);
    }
    for(i = 0; i<strl.size() ; i++){
        str = strl[i];
        if(str.isEmpty())continue;
         qDebug()<<"From pick_up_results: "<<str;
        for(j = KEY_START;j<=KEY_STOP;j++){
            if(str.contains(capture_key_map[j])){
                switch(j){
                case CMDEXITSUCCESSKEY:
                case CMDEXITFAILKEY:
                    emit cmd_result(capture_key_map[j]);
                    break;
                case TYPEKEY:
                    break;
                case MACKEY:
                case LAN1KEY:
                case LAN2KEY:
                case LEDKEY:
                case UPMTDKEY:
                case CONFIGKEY:
                case RESETKEY:
                case WATCHDOGKEY:
                case WIFIKEY:
                case LICENSEKEY:
                case UPGRADEKEY:
                    if(str.contains(capture_key_map[PASSKEY]))
                    {
                        ui->resulttable->setItem(dev_count, j,
                                                 new QTableWidgetItem(capture_key_map[PASSKEY]));
                    }else if(str.contains(capture_key_map[FAILKEY])){
                        ui->resulttable->setItem(dev_count, j,
                                                 new QTableWidgetItem(capture_key_map[FAILKEY]));
                    }
                    break;
                case SSHLOGINKEY:
                    emit cmd_result(capture_key_map[CMDEXITSUCCESSKEY]);
                    break;
                default:
                    break;
                }
            }
        }
    }
}

/*
 * Check to find out wether the ssh ip could be ping
*/
bool MainWindow::check_dhcpoffer_ip(QString ip)
{
    data_map["dhcp_ip_cmd"] = " ping  "+ ip + " -c 3 ";
    return run_one_cmd(data_map["dhcp_ip_cmd"]);
}

bool MainWindow::run_one_cmd(QString cmd)
{
    run_one_cmd_res = false;
    if(cmd == data_map["ssh_cmdline"]){
        cmd += "\n";
        delay_success_timer->start(5000);
    }
    else if(cmd == opt_map[SPECIALCMDEXIT] || cmd == opt_map[SPECIALCMDSTARTSHELL]){
        cmd +="\n";
        ui->qterm->sendText(cmd);
        return true;
    }
    else
        cmd += " && echo "+capture_key_map[CMDEXITSUCCESSKEY]+" || echo "+capture_key_map[CMDEXITFAILKEY] + "\n";
    ui->qterm->sendText(cmd);
    while(!is_run_one_cmd_next){
        QCoreApplication::processEvents();
        QThread::usleep(1000);
        delay_fail_timer->start(100000);
    }
    delay_fail_timer->stop();
    qDebug()<<"Result of Run One CMD: "<<(run_one_cmd_res==true?"true":"false");
    is_run_one_cmd_next = false;
    return run_one_cmd_res;
}

void MainWindow::emit_fail_result_timer()
{
    delay_fail_timer->stop();
    emit cmd_result(capture_key_map[CMDTIMEOUTFAILKEY]);
}

void MainWindow::emit_success_result_timer()
{
    delay_success_timer->stop();
    emit cmd_result(capture_key_map[CMDEXITSUCCESSKEY]);
}

void MainWindow::cmd_result_slot(QString res)
{
    is_run_one_cmd_next = true;
    if(res == capture_key_map[CMDEXITSUCCESSKEY])
        run_one_cmd_res = true;
    else
        run_one_cmd_res = false;
}

bool MainWindow::is_current_month_and_day(QString Month, QString Day)
{
    QDateTime time = QDateTime::currentDateTime();
    QLocale locale = QLocale(QLocale::English, QLocale::China);
    QString month = locale.toString(time, "MMM");
    QString day = locale.toString(time, "d");
    if(month != Month || day != Day)
        return false;
    return true;
}

/*
 *Try to modify this function to read the log file in reverse mode.(Not been Modified Now!20150921)
 *First read the last line of the log file, then the second line from the bottom, etc...
 *To implement this feature, QList is considered to be a good choice.
 * I insert every line (a QString) whitch contains substring 'DHCPOFFER' and maps the current month and day.
 * Then use pop_back to get element at the bottom of the line. If check OK, it would empty the QList.
 * I doubt that would be more efficient, however, I think it could be usefully!
*/
bool MainWindow::autodetect_dhcpd_log_file()
{
    if(is_detect_ip && check_dhcpoffer_ip(data_map["ssh_ip"]))
        return true;
    is_detect_ip = false;
    QFileInfo qinfo(data_map["dhcp_log_file"]);
    if(!qinfo.isFile()){
        QMessageBox::critical(this, tr("Dhcp Log File doesn't Exist!"), tr("Can not find dhcpd log file: %1<br>"
                                                                  "Please set the dhcpd log file to the correct path!").arg(data_map["dhcp_log_file"]));
        return false;
    }
    QFile file(data_map["dhcp_log_file"]);
    if(!file.open(QFile::ReadOnly | QFile::Text)){
        QMessageBox::critical(this, tr("Could not open log file!"), tr("Fail to Open dhcpd log file: %1<br>"
                                                                       "Ensure you have the proper access mode to this file!"
                                                                       "(May be the logfile is too large to read!:-(").arg(data_map["dhcp_log_file"]));
        return false;
    }
    QTextStream in(&file);
    QString line;
    QString ip;
    QStringList strl;
    int strl_size ;
    line = in.readLine();
    while(!line.isEmpty()){
        line.replace(QRegExp("\\s{1,}"), " ");
        strl = line.split(" ");
        if(!is_current_month_and_day(strl[0], strl[1])){
            line = in.readLine();
            continue;
        }
        strl_size = strl.size();
        if(strl_size > 8 && strl[5] == data_map["dhcp_log_file_filter_key_word"]){
            ip = strl[7];
            if(!last_ip.contains("#"+ip+"#") && check_dhcpoffer_ip(ip)){
                last_ip = "";
                data_map["ssh_ip"] = ip;
                data_map["ssh_cmdline"] = "ssh   "+data_map["ssh_user"]+ "@"+data_map["ssh_ip"]+"\n";
                is_detect_ip = true;
                return true;
            }else{
                last_ip.append("#"+ ip+"#");
            }
        }else if(strl_size > 9 && strl[6] == data_map["dhcp_log_file_filter_key_word"]){
            ip = strl[8];
            if(!last_ip.contains("#"+ip+"#") && check_dhcpoffer_ip(ip)){
                last_ip = "";
                data_map["ssh_ip"] = ip;
                data_map["ssh_cmdline"] = "ssh   "+data_map["ssh_user"]+ "@"+data_map["ssh_ip"]+"\n";
                is_detect_ip = true;
                return true;
            }else{
                last_ip.append("#"+ip+"#");
            }
        }
        line = in.readLine();
    }
    last_ip = "";
    QMessageBox::critical(this, tr("fail to detetct dhcp board ip"), tr("Could not detect dhcp ip in autodetector,<br>"
                                                                        "may be you should connect your board"));
    return false;
}

bool MainWindow::start_ssh_connection()
{
    if(!run_one_cmd("which ssh")){
        QMessageBox::critical(this, tr("Command SSH not found"), tr("ssh command not found on this computer!<br>"
                                                                    "May be you should yum install ssh"));
        return false;
    }
    if(run_one_cmd("which sshpass"))
        data_map["ssh_cmdline"] = "sshpass -p "+data_map["ssh_password"]+" ssh -o StrictHostKeyChecking=no "+data_map["ssh_user"]+"@"+data_map["ssh_ip"]+"\n";
    else
        data_map["ssh_cmdline"] = "ssh -o StrictHostKeyChecking=no "+data_map["ssh_user"]+"@"+data_map["ssh_ip"]+"\n";
    return run_one_cmd(data_map["ssh_cmdline"]);
}

void MainWindow::update_time()
{
    ui->statusBar->showMessage(get_cur_time_and_date());
}

QString MainWindow::get_cur_time_and_date()
{
    QTime qtime = QTime::currentTime();
    QString strtime = qtime.toString(" h:m:s     ap");
    strtime.prepend("                        ");
    QDate qdate = QDate::currentDate();
    QString strdate = qdate.toString("yyyy, MMMM d, dddd");
    strdate.append(strtime);
    return strdate;
}

void MainWindow::xlsx_save(QString fileName)
{
    QXlsx::Document xlsx;
    int col = 0, row = 0;
    QString content;
    QStringList strl;
    strl<<"TYPE"<<"MAC"<<"WAN"<<"LAN"<<"WIFI"<<"SN"<<"LICENSE"<<"OEM"<<"UPGRADE";
    for(col = 0; col < 9; col++)
        xlsx.write( 1, col+1, strl[col]);
    for(row = 0; row <dev_count; row++){
        for(col = 0; col < 9; col++){
              content = ui->resulttable->item(row, col)->text();
              xlsx.write(row+2, col+1, content);
        }
    }
    xlsx.saveAs(fileName);
}

void MainWindow::on_startService_clicked()
{
    if(is_ssh)
        return;
    if(!is_config)
        if(!tryload_config(data_map["config_out"]))
            QMessageBox::information(this, tr("Error while loading config file"), tr("You Can Set The Config File Path manually!"
                                                                                     "Of Just Inore This Information to use Default Setting"));
    if(!autodetect_dhcpd_log_file()){
        QMessageBox::critical(this, tr("Error detect dhcp file and ip"), tr("auto detect dhcp log file func return false"));
        return;
    }
    if(!start_ssh_connection())
        QMessageBox::critical(this, tr("Error!"), tr("Fail to Start SSH Connect!<br>"
                                                      "<b>User: %1<br>"
                                                      "HOST IP: %1</b>").arg(data_map["ssh_user"].arg(data_map["ssh_ip"])));
    is_ssh = true;
    unsigned int i;
    QString cur_dev;
    cur_dev = ui->devtypebox->currentText();
    ui->resulttable->setItem(dev_count, TYPEKEY, new QTableWidgetItem(cur_dev));
    for(i = LAN1KEY; i <= WATCHDOGKEY; i++){
            ui->resulttable->setItem(dev_count, i, new QTableWidgetItem(capture_key_map[NAKEY]));
    }
    qDebug()<<"Start Running Start Script.....";
    if(!run_vjjt_test_script(data_map["start_sh"]))
        QMessageBox::critical(this, tr("Error!"), tr("Some Error Occur in Starting Vjjt Test Service!"));
    ui->resulttable->setRowCount(++dev_count+1);
}

void MainWindow::on_StopService_clicked()
{
    if(!is_ssh)
        return;
    qDebug()<<"Start Running Stop Script......";
    if(!run_vjjt_test_script(data_map["stop_sh"]))
        QMessageBox::critical(this, tr("Error!"), tr("Some Error Occur in Stoping Vjjt Test Service!"));
    run_one_cmd("exit");
    is_ssh = false;
}

void MainWindow::on_actionAbout_triggered()
{
    QMessageBox::about(this, tr("About This Demo"), tr(
                                                       "<b>This program is free software; you can redistribute it and/or modify  "
                                                       " it (the vjjttest part) under the terms of the GNU General Public License version 2 as"
                                                       " published by the Free Software Foundation.</b><br>"
                                                       "It is "
                                                      "Developed By DoggerAndPigger Jeffery at 20150828~20150905 VJJT.Corp<br>"
                                                      "If you have any questions, please contact <b>1960949503@qq.com</b><br>"
                                                       "<b>However, you should know that you need root privilege to run this demo!</b>"
                                                       ));
}

void MainWindow::on_actionAbout_Qt_triggered()
{
    QMessageBox::aboutQt(this, tr("About Qt"));
}

void MainWindow::on_actionExit_triggered()
{
    if(is_edit_tablewidget)
    {
        if(data_map["xlsx_out"].isEmpty())
            ui->actionExport_To_Excel->triggered();
        else
            xlsx_save(data_map["xlsx_out"]);
    }
    this->close();
}

void MainWindow::on_actionExport_To_Excel_triggered()
{
    QString xlsx_fileName = QFileDialog::getSaveFileName(this, tr("Save xlsx Name"), tr("results.xlsx"),  tr("xlsx ( *xlsx)"));
    if(!xlsx_fileName.isEmpty())
    {
        xlsx_save(xlsx_fileName);
    }
}

void MainWindow::on_actionSetting_triggered()
{
    settingdialog->exec();
    if(settingdialog->can_be_load){
        data_map["ssh_user"] = settingdialog->get_ssh_user();
        data_map["ssh_ip"] = settingdialog->get_ssh_ip();
        data_map["ssh_password"] = settingdialog->get_ssh_password();
        data_map["dhcp_log_file"] = settingdialog->get_dhcp_log_file();
        data_map["ssh_cmdline"] = "ssh  "+data_map["ssh_user"]+ "@"+ data_map["ssh_ip"]+"\n";
    }
}

void MainWindow::on_actionSSH_Connect_triggered()
{
    ui->qterm->sendText(data_map["ssh_cmdline"]);
}

void MainWindow::on_actionRandom_Mac_Address_Generotor_triggered()
{
    qsrand(time(NULL)+QTime::currentTime().msec());
    QString mac="B0:96:6C:",tmp;
    unsigned int tp,i;
    for(i=0;i<3 ;i++){
        tp = qrand()%32;
        tmp.sprintf("%s%X%s", (tp<16 ? "0":""), tp, (i<4 ? ":":""));
        mac.append(tmp);
    }
    data_map["rand_mac"]  = mac;
    QMessageBox::information(this, tr("Random Mac Address"), tr("Your Mac Address Generated is : <br>"
                                                                "<b>%1</b>").arg(data_map["rand_mac"]));
}

void MainWindow::on_actionTarget_Board_IP_AutoDetector_triggered()
{
    if(autodetect_dhcpd_log_file())
        QMessageBox::information(this, tr("result"), tr("Dedected IP: <b>%1</b>").arg(data_map["ssh_ip"]));
    else
        QMessageBox::information(this, tr("result"), tr("Could not dedected IP now!<br>"
                                                         "Current Ip is:<b> %1</b>").arg(data_map["ssh_ip"]));
}

void MainWindow::on_actionSave_Config_File_triggered()
{
    QString save_fileName = QFileDialog::getSaveFileName(this, tr("Save Config File"), tr("vjjtUI.cfg"), tr("cfg (*.cfg)"));
    if(!save_fileName.isEmpty()){
        QFile file(save_fileName);
        if(!file.open(QFile::WriteOnly | QFile::Text)){
            QMessageBox::warning(this, tr("Application"),
                                tr("Can not write file %1: %2")
                                 .arg(save_fileName)
                                 .arg(file.errorString()));
        }
        QTextStream out(&file);
        QString line;
        for(int i = OPT_START ; i<=OPT_STOP; i++){
            line = opt_map[i];
            line.append("=");
            line.append(data_map[opt_map[i]]);
            line.append("\n");
            out<<line;
        }
    }
}

void MainWindow::on_actionLoad_Config_File_triggered()
{
    QString load_fileName = QFileDialog::getOpenFileName(this, tr("Load Config File"), data_map["config_out"], tr("cfg (*.cfg)"));
    if(!load_fileName.isEmpty()){
        tryload_config(load_fileName);
    }
}

void MainWindow::on_actionText_Editor_triggered()
{
    texteditor = new TextEditor;
    texteditor->show();
}

void MainWindow::on_actionAll_Config_triggered()
{
    texteditor = new TextEditor;
    QString content = "# Use This Editor To Edit The Config File.\n";
    for(int i = OPT_START; i<= OPT_STOP; i++){
        content.append(opt_map[i]);
        content.append("=");
        content.append(data_map[opt_map[i]]);
        content.append("\n");
    }
    texteditor->textEdit->setPlainText(content);
    texteditor->show();
}

void MainWindow::on_devtypebox_currentTextChanged(const QString &arg1)
{
    dev_type = arg1;
    data_map["config_test_board_config_path"]= "/result/config-"+dev_type+".bin";
    data_map["license_test"] = generate_license(dev_type);//templine
    qDebug()<<"Current Device Type: "<<dev_type;
}
